import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import {
  Table,
  Icon,
  Divider,
  Form,
  Select,
  DatePicker,
  Input,
  Card,
  Tag,
  Avatar,
  Checkbox,
  Rate,
  Progress,
  Button,
  Dropdown,
  Row,
  Col,
  Modal,
  Collapse,
  message,
  List,
  Radio,
  Spin,
} from 'antd';

import FooterToolbar from 'components/FooterToolbar';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import ImageUploader from '../../../components/Falcon/Attachment/ImageUploader';
import AttachmenTable from '../../../components/Falcon/Attachment/AttachmentTable';
import ApplyOrderDisplayer from '../../../components/Falcon/ApplyOrderDisplayer';
import querystring from 'querystring';
import styles from './style.less';
import { routerRedux } from '../../../../node_modules/dva/router';
import { solo } from '../../../common/solo';

const Panel = Collapse.Panel;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const Option = Select.Option;

const formItemLayout = {
  labelCol: {
    span: 24,
  },
  wrapperCol: {
    span: 24,
  },
};

const formItemLayoutOfHorizon = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 19,
  },
};

@connect(({ risk, apply }) => ({
  risk,
  apply,
}))
@Form.create()
export default class PickCarEditorDetail extends PureComponent {
  state = {
    width: '100%',
    projectId: '',
    taskId: '',
    assetGpsData: [],

    imageMap: {
      invoiceImg: [],
      insuranceImg: [],
    },

    attachsMap: {
      pickCar: [],
      driveLicenseImg: [],
      carQualified: [],
      carRegister: [],
      otherImg: [],
    },

    loadingPickCar: false,
  };

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    this.setState({
      projectId: params.id,
      taskId: params.taskId,
    });
    // console.log('this.state.assetGps', this.state.assetGpsData);
    dispatch({
      type: 'apply/getPickCar',
      payload: {
        projectId: params.id,
      },
      callback: () => {
        const { apply } = this.props;
        const { pickCarDetails } = apply;
        // const { pickCar } = pickCarDetails;
        // pickCar &&
        //   this.setState({
        //     assetGpsData: pickCar.GPS,
        //   });
        // console.log("pickCarDetails.invoice.attachs", pickCarDetails)
        let imageMap = this.state.imageMap;
        if (pickCarDetails.invoice.attachs.length > 0) {
          for (let i = 0; i < pickCarDetails.invoice.attachs.length; i++) {
            imageMap.invoiceImg.push({
              key: pickCarDetails.invoice.attachs[i],
              uid: pickCarDetails.invoice.attachs[i],
              name: pickCarDetails.invoice.attachs[i],
              status: 'done',
              url: solo.imgShow + pickCarDetails.invoice.attachs[i],
            });
          }
        }
        if (pickCarDetails.insurance.attachs.length > 0) {
          for (let i = 0; i < pickCarDetails.insurance.attachs.length; i++) {
            imageMap.insuranceImg.push({
              key: pickCarDetails.insurance.attachs[i],
              uid: pickCarDetails.insurance.attachs[i],
              name: pickCarDetails.insurance.attachs[i],
              status: 'done',
              url: solo.imgShow + pickCarDetails.insurance.attachs[i],
            });
          }
        }

        let attachsMap = this.state.attachsMap;
        if (pickCarDetails.attachs.pickCar.length > 0) {
          for (let i = 0; i < pickCarDetails.attachs.pickCar.length; i++) {
            attachsMap.pickCar.push({
              key: pickCarDetails.attachs.pickCar[i],
              uid: pickCarDetails.attachs.pickCar[i],
              name: pickCarDetails.attachs.pickCar[i],
              status: 'done',
              url: solo.imgShow + pickCarDetails.attachs.pickCar[i],
            });
          }
        }
        if (pickCarDetails.attachs.driveLicenseImg.length > 0) {
          for (let i = 0; i < pickCarDetails.attachs.driveLicenseImg.length; i++) {
            attachsMap.driveLicenseImg.push({
              key: pickCarDetails.attachs.driveLicenseImg[i],
              uid: pickCarDetails.attachs.driveLicenseImg[i],
              name: pickCarDetails.attachs.driveLicenseImg[i],
              status: 'done',
              url: solo.imgShow + pickCarDetails.attachs.driveLicenseImg[i],
            });
          }
        }
        if (pickCarDetails.attachs.carQualified.length > 0) {
          for (let i = 0; i < pickCarDetails.attachs.carQualified.length; i++) {
            attachsMap.carQualified.push({
              key: pickCarDetails.attachs.carQualified[i],
              uid: pickCarDetails.attachs.carQualified[i],
              name: pickCarDetails.attachs.carQualified[i],
              status: 'done',
              url: solo.imgShow + pickCarDetails.attachs.carQualified[i],
            });
          }
        }
        if (pickCarDetails.attachs.carRegister.length > 0) {
          for (let i = 0; i < pickCarDetails.attachs.carRegister.length; i++) {
            attachsMap.carRegister.push({
              key: pickCarDetails.attachs.carRegister[i],
              uid: pickCarDetails.attachs.carRegister[i],
              name: pickCarDetails.attachs.carRegister[i],
              status: 'done',
              url: solo.imgShow + pickCarDetails.attachs.carRegister[i],
            });
          }
        }
        if (pickCarDetails.attachs.otherImg.length > 0) {
          for (let i = 0; i < pickCarDetails.attachs.otherImg.length; i++) {
            attachsMap.otherImg.push({
              key: pickCarDetails.attachs.otherImg[i],
              uid: pickCarDetails.attachs.otherImg[i],
              name: pickCarDetails.attachs.otherImg[i],
              status: 'done',
              url: solo.imgShow + pickCarDetails.attachs.otherImg[i],
            });
          }
        }
        this.setState({
          attachsMap,
          imageMap,
          loadingPickCar: true,
        });
      },
    });
    window.addEventListener('resize', this.resizeFooterToolbar);
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.resizeFooterToolbar);
  }

  resizeFooterToolbar = () => {
    const sider = document.querySelectorAll('.ant-layout-sider')[0];
    const width = `calc(100% - ${sider.style.width})`;
    if (this.state.width !== width) {
      this.setState({ width });
    }
  };

  handleSumbitPickCar = () => {
    const { dispatch } = this.props;
    const { validateFieldsAndScroll } = this.props.form;
    validateFieldsAndScroll((error, values) => {
      if (!error) {
        dispatch({
          type: 'apply/commitPickCar',
          payload: {
            projectId: this.state.projectId,
            taskId: this.state.taskId,
            ...values,
          },
          callback: () => {
            const { apply: { applyResult } } = this.props;
            if (applyResult.code == 200) {
              message.success('提交成功');
              dispatch(routerRedux.push('/apply/pickCarEditorList'));
              // dispatch({
              //   type: 'apply/getPickCar',
              //   payload: {
              //     projectId: this.state.projectId,
              //   },
              // });
            } else {
              message.error(applyResult.message);
            }
          },
        });
      }
    });
  };

  handleImageUploaded = (fieldName, fileList) => {
    switch (fieldName) {
      case '发票':
        this.setState({
          imageMap: { ...this.state.imageMap, invoiceImg: fileList },
        });
        break;
      case '保单':
        this.setState({
          imageMap: { ...this.state.imageMap, insuranceImg: fileList },
        });
        break;
    }
  };

  // handleAssetGPSValue0 = e => {
  //   let GPS = this.state.assetGpsData;
  //   GPS[0] = e.target.value;
  //   this.setState({ assetGpsData: GPS });
  // };
  // handleAssetGPSValue1 = e => {
  //   let GPS = this.state.assetGpsData;
  //   GPS[1] = e.target.value;
  //   this.setState({ assetGpsData: GPS });
  // };
  // handleAssetGPSValue2 = e => {
  //   let GPS = this.state.assetGpsData;
  //   GPS[2] = e.target.value;
  //   this.setState({ assetGpsData: GPS });
  // };
  // handleAssetGPSValue3 = e => {
  //   let GPS = this.state.assetGpsData;
  //   GPS[3] = e.target.value;
  //   this.setState({ assetGpsData: GPS });
  // };

  calcAttachmentData = pickCarDetails => {
    const { projectId } = this.state;
    const projectInfo = {
      projectId,
    };
    let attachmentData = [
      {
        key: '1',
        name: '提车照片',
        projectInfo: projectInfo,
        customerId: '',
        fieldName: 'pickCar',
        attachKind: '1620',
        maxCount: 10,
        files: [],
      },
      {
        key: '2',
        name: '行驶证',
        projectInfo: projectInfo,
        customerId: '',
        fieldName: 'driveLicenseImg',
        attachKind: '1680',
        maxCount: 2,
        files: [],
      },
      {
        key: '3',
        name: '合格证',
        projectInfo: projectInfo,
        customerId: '',
        fieldName: 'carQualified',
        attachKind: '1670',
        maxCount: 1,
        files: [],
      },
      {
        key: '4',
        name: '登记证',
        projectInfo: projectInfo,
        customerId: '',
        fieldName: 'carRegister',
        attachKind: '1660',
        maxCount: 1,
        files: [],
      },
      {
        key: '5',
        name: '其他',
        projectInfo: projectInfo,
        customerId: '',
        fieldName: 'otherImg',
        attachKind: '1690',
        maxCount: 10,
        files: [],
      },
    ];

    const { attachs } = pickCarDetails;

    return attachmentData.map((attachmentMetaInfo, index) => {
      const { fieldName } = attachmentMetaInfo;
      const imageKeyList = attachs[fieldName];
      if (!imageKeyList) {
        return attachmentMetaInfo;
      }
      const imageInfoList = imageKeyList.map(key => {
        return {
          key,
          url: `${solo.imgShow}${key}`,
          status: 'done',
          uid: key,
          name: key,
        };
      });
      attachmentMetaInfo.files = imageInfoList;
      return attachmentMetaInfo;
    });
  };

  handleRemoveImage = (fieldName, fileInfo) => {
    const { dispatch } = this.props;
    // console.log("handleRemoveImage", fileInfo)
    dispatch({
      type: 'apply/deleteFile',
      payload: {
        fileId: fileInfo.key,
      },
    });
  };

  render() {
    // const { risk } = this.props;
    const { apply: { pickCarDetails, applyLoading, applyPage, applyPickCarLoading } } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { loadingPickCar } = this.state;

    return (
      <PageHeaderLayout title="提车服务">
        {/* {console.log(pickCarDetails) } */}
        {applyLoading ? (
          <div className={styles.spinContainer}>
            <Spin size="large" />
          </div>
        ) : (
          loadingPickCar &&
          pickCarDetails && (
            <div>
              <Card title="资产信息">
                <Form>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label="车型" {...formItemLayout}>
                        {getFieldDecorator('carType', {
                          initialValue: pickCarDetails.asset.carType,
                        })(<Input disabled />)}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="厂商指导价" {...formItemLayout}>
                        {getFieldDecorator('msrp', {
                          initialValue: pickCarDetails.asset.msrp,
                        })(<Input disabled />)}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="经销商" {...formItemLayout}>
                        {getFieldDecorator('dealerName', {
                          initialValue: pickCarDetails.asset.dealerName,
                        })(<Input disabled />)}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label="经销商账号" {...formItemLayout}>
                        {getFieldDecorator('bankAccount', {
                          initialValue: pickCarDetails.asset.bankAccount,
                        })(<Input disabled />)}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="经销商报价" {...formItemLayout}>
                        {getFieldDecorator('dealerPrice', {
                          initialValue: pickCarDetails.asset.dealerPrice,
                        })(<Input disabled />)}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </Card>

              <Card title="提车情况" style={{ marginTop: '16px' }}>
                <Form>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label="车架号" {...formItemLayout}>
                        {getFieldDecorator('carFrame', {
                          initialValue: pickCarDetails.asset.carFrame,
                        })(<Input placeholder="请输入" />)}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="车牌号" {...formItemLayout}>
                        {getFieldDecorator('licensePlate', {
                          initialValue: pickCarDetails.pickCar.licensePlate,
                        })(<Input placeholder="请输入" />)}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="行驶证号码" {...formItemLayout}>
                        {getFieldDecorator('licenseDrive', {
                          initialValue: pickCarDetails.pickCar.licenseDrive,
                        })(<Input placeholder="请输入" />)}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label="车辆合格证编号" {...formItemLayout}>
                        {getFieldDecorator('licenseCar', {
                          initialValue: pickCarDetails.pickCar.licenseCar,
                        })(<Input placeholder="请输入" />)}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="车辆登记证编号" {...formItemLayout}>
                        {getFieldDecorator('licenseRegister', {
                          initialValue: pickCarDetails.pickCar.licenseRegister,
                        })(<Input placeholder="请输入" />)}
                      </FormItem>
                    </Col>
                  </Row>
                  {/* <FormItem label="GPS编号" {...formItemLayout}>
                      <Row gutter={24}>
                        <Col span={6}>
                          <Input
                            placeholder="请输入"
                            defaultValue={this.state.assetGpsData[0]}
                            // value={this.state.assetGpsData[0]}
                            onChange={this.handleAssetGPSValue0}
                          />
                        </Col>
                        <Col span={6}>
                          <Input
                            placeholder="请输入"
                            // value={this.state.assetGpsData[1]}
                            onChange={this.handleAssetGPSValue1}
                          />
                        </Col>
                        <Col span={6}>
                          <Input
                            placeholder="请输入"
                            // value={this.state.assetGpsData[2]}
                            onChange={this.handleAssetGPSValue2}
                          />
                        </Col>
                        <Col span={6}>
                          <Input
                            placeholder="请输入"
                            // value={this.state.assetGpsData[3]}
                            onChange={this.handleAssetGPSValue3}
                          />
                        </Col>
                      </Row>
                    </FormItem> */}
                </Form>
              </Card>

              <Card title="发票信息" style={{ marginTop: '16px' }}>
                <Form>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label="上传发票" {...formItemLayout}>
                        <ImageUploader
                          maxCount={10}
                          fieldName="发票"
                          label="发票"
                          key={1}
                          size="small"
                          showRemoveIconType={true}
                          onRemoveImage={this.handleRemoveImage}
                          attachmentData={{
                            projectId: this.state.projectId, //业务ID
                            customerId: '', //客户ID
                            attachType: '0', //0：图片；1：视频
                            attachKind: '1630', //附件种类
                            type: '发票', //图片类型
                          }}
                          fileList={this.state.imageMap.invoiceImg}
                          onImageUploaded={this.handleImageUploaded}
                        />
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="发票编号" {...formItemLayout}>
                        {getFieldDecorator('invoiceNumber', {
                          initialValue: pickCarDetails.invoice.invoiceNumber,
                        })(<Input placeholder="请输入" />)}
                        {/* <Button>识别发票信息</Button> */}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="开票金额" {...formItemLayout}>
                        {getFieldDecorator('invoicePrice', {
                          initialValue: pickCarDetails.invoice.invoicePrice,
                        })(<Input placeholder="请输入" />)}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="开票单位" {...formItemLayout}>
                        {getFieldDecorator('invoiceCompany', {
                          initialValue: pickCarDetails.invoice.invoiceCompany,
                        })(<Input placeholder="请输入" />)}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </Card>
              <Card title="保险信息" style={{ marginTop: '16px' }}>
                <Form>
                  <Row gutter={16}>
                    <Col span={8}>
                      <FormItem label="上传保单" {...formItemLayout}>
                        <ImageUploader
                          maxCount={10}
                          fieldName="保单"
                          label="保单"
                          key={1}
                          size="small"
                          showRemoveIconType={true}
                          onRemoveImage={this.handleRemoveImage}
                          attachmentData={{
                            projectId: this.state.projectId, //业务ID
                            customerId: '', //客户ID
                            attachType: '0', //0：图片；1：视频
                            attachKind: '1640', //附件种类
                            type: '保单', //图片类型
                          }}
                          fileList={this.state.imageMap.insuranceImg}
                          onImageUploaded={this.handleImageUploaded}
                        />
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="发票编号" {...formItemLayout}>
                        {getFieldDecorator('insuranceNumber', {
                          initialValue: pickCarDetails.insurance.invoiceNumber,
                        })(<Input placeholder="请输入" />)}
                        {/* <Button>识别发票信息</Button> */}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="开票金额" {...formItemLayout}>
                        {getFieldDecorator('insurancePrice', {
                          initialValue: pickCarDetails.insurance.invoicePrice,
                        })(<Input placeholder="请输入" />)}
                      </FormItem>
                    </Col>
                    <Col span={8}>
                      <FormItem label="开票单位" {...formItemLayout}>
                        {getFieldDecorator('insuranceCompany', {
                          initialValue: pickCarDetails.insurance.invoiceCompany,
                        })(<Input placeholder="请输入" />)}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </Card>
            </div>
          )
        )}
        {/* {JSON.stringify(this.state.attachsMap)} */}
        {pickCarDetails && (
          <Card title="附件管理" style={{ marginTop: '16px' }}>
            <AttachmenTable
              applyDisabled={false}
              data={this.calcAttachmentData(pickCarDetails)}
              projectInfo={{ projectId: this.state.projectId }}
              onAttachmentChanged={this.hanleAttachmentChanged}
              onAttachmentRemove={this.handleRemoveImage}
            />
          </Card>
        )}
        <FooterToolbar style={{ width: this.state.width }}>
          <Button type="primary" onClick={this.handleSumbitPickCar} loading={applyPickCarLoading}>
            提交
          </Button>
        </FooterToolbar>
      </PageHeaderLayout>
    );
  }
}
